<template>
  <view class="container bg-img flex-1">
    <view class="fixed -z-10 top-0 left-0">
      <up-count-down
        :time="estimatedTime * 1000"
        format="HH:mm:ss"
        @change="changTime"
        @finish="end"
      ></up-count-down>
    </view>

    <!-- <view
      class="img-A"
      :class="isBigSreen ? 'mt-[3.4%]' : 'mt-[6.4%]'"
      v-if="data.size == '9:16'"
    >
      <image src="@/static/title.png" class="title-img" mode="widthFix"></image>
      <view class="relative w-full flex justify-center">
        <view class="stamp">
          <image
            class="w-full h-full"
            :src="data.ai_image"
            v-if="data.ai_image"
            mode="widthFix"
          ></image>
          <view v-else class="placeholder"></view>
        </view>
        <image class="zhen" src="@/static/zhen.png"></image>
      </view>
    </view> -->
    <view class="img-B" :class="isBigSreen ? 'mt-[10%]' : 'mt-[16%]'">
      <image src="@/static/title.png" class="title-img" mode="widthFix"></image>
      <view class="relative w-full flex justify-center">
        <view class="stamp">
          <image
            class="w-full h-full pb-1"
            :src="data.ai_image"
            v-if="data.ai_image"
            mode="widthFix"
          ></image>
          <view v-else class="placeholder"></view>
        </view>
        <!-- <image :src="data.ai_image" class="stamp" mode="widthFix"></image> -->
        <image
          class="zhen"
          src="@/static/zhen.png"
          :class="isBigSreen ? 'top-[-0.4%]' : 'top-[-0.8%]'"
        ></image>
      </view>
    </view>
    <view class="mt-8" v-if="!isBigSreen">
      <view class="flex mx-12 justify-between">
        <view
          class="btn flex items-center justify-center"
          @click="handleClick(0)"
        >
          <image class="w-[36rpx] h-[36rpx]" src="@/static/save.png"></image>
          <text class="pl-2">保存</text>
        </view>
        <view
          class="btn flex items-center justify-center"
          @click="handleClick(1)"
        >
          <image class="w-[36rpx] h-[36rpx]" src="@/static/share.png"></image>
          <text class="pl-2">分享</text>
        </view>
      </view>
    </view>
    <view class="text-center" :class="isBigSreen ? 'mt-[8%]' : 'mt-[6%]'">
      <text
        class="alginia mr-6"
        :class="isBigSreen ? 'text-2main' : 'text-xl'"
        @click="goHome"
        >回到首页</text
      >
      <text
        class="alginia ml-6"
        :class="isBigSreen ? 'text-2main' : 'text-xl'"
        @click="review"
        >再次参与</text
      >
    </view>

    <view class="slide" v-if="isBigSreen">
      <view v-if="open" class="content">
        <view class="circle light mb-30" @click="printImg()"> 打印 </view>
        <view class="circle light mb-30" @click="handleClick(1)"> 保存 </view>
        <view class="circle dark mb-30" @click="handleClick(1)"> 分享 </view>
        <view class="circle dark" @click="goHome"> 首页 </view>
      </view>
      <view class="jiantou">
        <view :class="open ? 'a mt-6' : 'b'" @click="handleSilde">
          <up-icon name="arrow-left-double" color="#8a8f96" size="36"></up-icon>
        </view>
      </view>
    </view>
    <up-overlay :show="show" @click="show = false">
      <view class="flex-1 flex justify-center items-center flex-col">
        <view class="bg-white p-5 rounded-2xl">
          <view>
            <canvas
              class="absolute -z-10"
              canvas-id="qrcode"
              style="width: 480rpx; height: 480rpx"
            />
            <image
              :src="shareimg"
              class="p-[1%]"
              :class="isBigSreen ? 'share_img_big' : 'share_img'"
            ></image>
          </view>
          <view
            class="text-center font-bold mt-3"
            style="color: #3d3d3d"
            :class="isBigSreen ? 'text-2main' : 'text-xl'"
          >
            用微信扫码打开进行分享
          </view>
        </view>
        <view class="mt-4" @click="show = false">
          <up-icon
            name="close-circle-fill"
            :size="isBigSreen ? 48 : 24"
            color="#fff"
          ></up-icon>
        </view>
      </view>
    </up-overlay>
    <up-overlay :show="showAi" zIndex="666">
      <view class="bg-back flex-1 w-full">
        <view class="flex justify-center mt-[25%] flex-col items-center">
          <view class="clock">
            <!-- <view class="hand hour-hand"></view>
            <view class="hand minute-hand"></view> -->
            <image
              src="@/static/time.png"
              class="w-full h-full"
              mode="widthFix"
            ></image>
          </view>
          <view class="text-main font-bold mt-7"
            >AI作图中，等待时间约{{ nowTime }}s</view
          >
        </view>
        <view
          class="mx-[4%] bg-white mt-[10%] pb-[10%]"
          :class="isBigSreen ? 'rounded-[40rpx]' : 'rounded-[20rpx]'"
        >
          <view class="px-[5%] py-[4%] text-justify" style="line-height: 1.8">
            <div>
              {{ displayedText
              }}<span v-if="isOutputting" class="cursor pl-[1%] text-[#2567EC]"
                >|</span
              >
            </div>
          </view>
        </view>
      </view>
    </up-overlay>
    <view
      class="text-white fixed bottom-[4%] left-[2.2%]"
      :class="isBigSreen ? 'text-2main' : 'text-xl'"
      >该图片由AI生成</view
    >
  </view>
</template>

<script setup>
import jweixin from "weixin-js-sdk";
import uQrCode from "@/utils/uQrCode.js";
import printJS from "print-js";
import {
  createAiPic,
  saveShare,
  downloadImg,
  downloadBinaryFileH5,
  printPic,
  jssdkConfig,
} from "@/api/index.js";

import { onLoad, onReady, onUnload } from "@dcloudio/uni-app";
import { ref, reactive, computed, watch } from "vue";

const isBigSreen = computed(() => {
  return uni.getSystemInfoSync().windowWidth > 500;
});

const show = ref(false);
const showAi = ref(false);

const shareimg = ref("");

const data = reactive({
  ai_image: "",
  size: "",
  share_url: "",
});

// const phoneType = ref("Android");
// const getSys = () => {
//   if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
//     console.dir(navigator.userAgent);
//     phoneType.value = "ios";
//   } else if (/(Android)/i.test(navigator.userAgent)) {
//     phoneType.value = "Android";
//   } else {
//     phoneType.value = "PC电脑";
//   }
//   console.log(phoneType.value);
// };
// getSys();

const review = () => {
  uni.removeStorageSync("scene");
  uni.reLaunch({ url: "/pages/index/chooseKeyword" });
};

const getDetail = (id) => {
  createAiPic({ id, is_mobile: isBigSreen.value ? 0 : 1 }).then((res) => {
    Object.assign(data, res);
    if (isWeixinBrowser()) {
      share();
    }
  });
};
const getDetailAi = (dataa) => {
  // str.value = dataa.scene_text;
  data.size = dataa.size;
  Object.assign(data, dataa);
  if (isWeixinBrowser()) {
    share();
  }
  // startOutput();
  createAiPic({ ...dataa, is_mobile: isBigSreen.value ? 0 : 1 })
    .then((res) => {
      Object.assign(data, res);
      console.log(data);
    })
    .catch((e) => {
      uni.showModal({
        title: "温馨提示",
        content: e,
        showCancel: false,
        success: () => {
          uni.navigateBack({
            delta: 3,
          });
        },
      });
    });
};

function isWeixinBrowser() {
  const ua = navigator.userAgent.toLowerCase();
  if (ua.match(/micromessenger/i) == "micromessenger") {
    return true;
  } else {
    return false;
  }
}
const handleClick = (type) => {
  if (!type) {
    if (isWeixinBrowser()) {
      return uni.showModal({
        title: "温馨提示",
        content: "在明信片区域长按后选择保存到手机",
        showCancel: false,
        confirmText: "我知道了",
      });
    }
    // console.log(data);
    // downloadBinaryFileH5(
    //   `https://ocean.firstmove.club/index.php/api/Postcard/download?share_id=${data.share_id}`,
    //   data.ai_image.split("/").pop()
    // );
    // return;
    // 创建一个a标签
    const link = document.createElement("a");
    // 设置下载的文件名
    const filename = "share_image.png";

    // 设置图片的BASE64格式作为下载内容
    link.href =
      import.meta.env.VITE_APP_BASE_URL +
      "/api/Postcard/download?share_id=" +
      data.share_id;
    link.download = data.ai_image.split("/").pop();

    // // // 触发点击事件
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    // downloadImg({
    //   share_id: data.share_id,
    // }).then((e) => {
    //   const file = e;
    //   const url = window.URL.createObjectURL(
    //     new Blob([file], {
    //       type: "image/jpeg",
    //     })
    //   );
    //   const link = document.createElement("a");
    //   link.style.display = "none";
    //   link.href = url;
    //   link.setAttribute("download", data.ai_image.split("/").pop());
    //   document.body.appendChild(link);
    //   link.click();
    //   document.body.removeChild(link);
    // });
    return;
    // saveImage();
  } else {
    if (isWeixinBrowser()) {
      share(1);
      uni.showModal({
        title: "温馨提示",
        content: "请点击右上角分享",
        showCancel: false,
        confirmText: "我知道了",
      });
      return;
    }
    show.value = true;
    codeInit();
  }
};

// onReady(() => {
//   if (isWeixinBrowser()) {
//     share();
//   }
// });
function share(type = 0) {
  let url = window.location.href;
  // let url = window.location.href + "?id=" + data.share_id;

  jssdkConfig({
    url: url,
    api_list: ["updateAppMessageShareData", "updateTimelineShareData"],
  }).then((res) => {
    console.log(res);
    jweixin.config({
      debug: false,
      appId: res.appId,
      timestamp: res.timestamp,
      nonceStr: res.nonceStr,
      signature: res.signature,
      jsApiList: res.jsApiList,
    });
    jweixin.ready(function () {
      const shareData = {
        title: "海洋文化公开课",
        desc: data.scene_text || data.scene_note,
        link: res.url,
        imgUrl:
          "https://lc-ocean.oss-cn-guangzhou.aliyuncs.com/ocean-2024/h5/images/shark.png",
        success: function (res) {
          console.log(res, 1111);
          if (type) {
            saveShare({
              share_id: data.share_id,
            });
          }
        },
        cancel: function (res) {},
      };

      //分享给朋友接口
      jweixin.updateAppMessageShareData(shareData);

      //分享到朋友圈接口
      jweixin.updateTimelineShareData(shareData);
    });
    jweixin.error(function (res) {
      // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
      console.log("anything wrong");
	  /*
      uni.showModal({
        title: "温馨提示",
        content: JSON.stringify(res),
        showCancel: false,
        confirmText: "我知道了",
      });
	  */
    });
  });
}

function codeInit() {
  uQrCode.make({
    canvasId: "qrcode",
    text: data.share_url,
    size: 200,
    margin: 0,
    backgroundColor: "#ffffff",
    foregroundColor: "#000000",
    fileType: "jpg",
    errorCorrectLevel: uQrCode.errorCorrectLevel.H,
    success: (res) => {
      shareimg.value = res;
      saveShare({
        share_id: data.share_id,
      });
    },
  });
}

const saveImage = () => {
  console.log(data);
  const img = data.ai_image;
  if (!img) return;

  // 创建一个虚拟的链接
  const link = document.createElement("a");
  link.href = img;
  link.setAttribute("download", data.ai_image.split("/").pop());
  // link.download = "image.png"; // 设置下载的文件名
  document.body.appendChild(link);

  // 模拟点击链接以触发下载
  link.click();

  // 移除链接
  document.body.removeChild(link);
};

const open = ref(true);
const handleSilde = () => {
  open.value = !open.value;
};

const printImg = () => {
  uni.showLoading({
    mask: true,
    title: "处理中",
  });
  printPic({
    share_id: data.share_id,
  })
    .then((res) => {
      uni.showModal({
        title: "温馨提示",
        content: res.msg,
        showCancel: false,
        confirmText: "我知道了",
      });
    })
    .finally(() => {
      uni.hideLoading();
    });
  // printJS(data.ai_image, "image");
};

onLoad(({ id, size }) => {
  if (!id) {
    // showAi.value = true;
    getDetailAi(uni.getStorageSync("scene") || {});
  }
  if (id) {
    // getDetailAi(uni.getStorageSync("scene") || {});
    // data.size = size;
    getDetail(id);
  }
});
onUnload(() => {
  uni.removeStorageSync("img");
});

const str = ref("");
const displayedText = ref("");
const isOutputting = ref(false);
const elapsedTime = ref(null);
const charInterval = 150; // 每个字符的输出间隔时间（毫秒）

const estimatedTime = ref(0);

const startOutput = () => {
  if (isOutputting.value) return;
  estimatedTime.value = ~~((str.value.length * charInterval) / 1000) + 4;

  isOutputting.value = true;
  displayedText.value = "";
  elapsedTime.value = null;

  let index = 0;
  const startTime = Date.now();

  const outputChar = () => {
    if (index < str.value.length) {
      displayedText.value += str.value[index];
      index++;
      setTimeout(outputChar, charInterval);
    } else {
      isOutputting.value = false;
      const endTime = Date.now();
      elapsedTime.value = ((endTime - startTime) / 1000).toFixed(2);
    }
  };

  outputChar();
};
const performAfterCompletion = () => {
  setTimeout(() => {
    if (data.ai_image) {
      showAi.value = false;
    }
  }, 1000);
};

const nowTime = ref("");
const changTime = (e) => {
  nowTime.value = e.seconds;
};
const end = () => {
  return false;
  // performAfterCompletion();
};

const goHome = () => {
  uni.removeStorageSync("scene");
  uni.reLaunch({
    url: "/pages/index/index",
  });
};
</script>

<style lang="scss" scoped>
.bg-img {
  background: url("https://lc-ocean.oss-cn-guangzhou.aliyuncs.com/ocean-2024/h5/images/bg.png")
    no-repeat;
  background-size: cover;
  .img-A {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    transform: rotate(356deg);
    width: 100%;

    .title-img {
      width: 60.1%;
      margin-bottom: 3.5%;
    }
    .stamp {
      width: 77%;
      aspect-ratio: 35/52;
      > image {
        border-radius: 20rpx;
      }
    }
    .placeholder {
      width: 100%;
      height: 0;
      padding-top: calc(52 / 35 * 100%);
      background-color: #eeede6; /* 或者任何合适的占位符颜色 */
      border-radius: 20rpx;
    }
    .zhen {
      width: 88rpx;
      height: 100rpx;
      position: absolute;
      top: -0.5%;
      right: 13%;
      transform: rotate(356deg);
    }
  }
  .img-B {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    transform: rotate(356deg);
    .title-img {
      width: 69.3%;
      margin-bottom: 3.5%;
    }
    .stamp {
      width: 93%;
      border-radius: 24rpx;
      aspect-ratio: 70/47;

      > image {
        border-radius: 20rpx;
        background-color: #fff;
      }
    }
    .placeholder {
      width: 100%;
      height: 0;
      padding-top: calc(47 / 70 * 100%);
      background-color: #eeede6; /* 或者任何合适的占位符颜色 */
      border-radius: 20rpx;
    }

    .zhen {
      width: 88rpx;
      height: 100rpx;
      position: absolute;
      right: 3.5%;
      transform: rotate(356deg);
    }
  }
  .btn {
    width: 128px;
    height: 80rpx;
    line-height: 80rpx;
    text-align: center;
    background: linear-gradient(180deg, #ffe480 0%, #ffe167 100%);
    box-shadow: 0px 6px 58px 0px rgba(196, 203, 214, 0.1036);
    border-radius: 252px;
    font-family: Source Han Serif CN, Source Han Serif CN;
    font-weight: 700;
    font-size: 36rpx;
    color: #1250b5;
  }
  .alginia {
    font-weight: 700;
    color: #ffffff;
    line-height: 32rpx;
    text-align: center;
    position: relative;
    &::after {
      position: absolute;
      content: "";
      height: 2rpx;
      width: 100%;
      background: #fff;
      bottom: 0;
      left: 0;
    }
  }
}
.share_img {
  width: 480rpx;
  height: 480rpx;
}
.share_img_big {
  width: 960rpx;
  height: 960rpx;
}
.slide {
  position: fixed;
  z-index: 888;
  right: 0;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;

  padding: 48rpx 20rpx;
  bottom: 24%;
  width: 248rpx;
  background: linear-gradient(
    180deg,
    rgba(53, 58, 64, 0.9) 0%,
    rgba(22, 23, 27, 0.9) 100%
  );
  border-radius: 64rpx 0rpx 0rpx 120rpx;
  border: 1rpx solid;
  // border-image: linear-gradient(
  //     180deg,
  //     rgba(66.00000366568565, 71.00000336766243, 80.00000283122063, 1),
  //     rgba(32.00000189244747, 35.00000171363354, 38.0000015348196, 1)
  //   )
  //   4 4;
  .circle {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    width: 188rpx;
    height: 188rpx;
    font-size: 48rpx;
    font-weight: 600;
    text-align: center;
    color: #c3c8cd;

    // .blur-3 {
    //   filter: blur(0.3px);
    // }

    &.light {
      font-weight: 600;
      color: #ffffff;
      text-shadow: 0px 0px 50px rgba(38, 171, 247, 0.2),
        0px 0px 20px rgba(99, 207, 255, 0.5);
      background: linear-gradient(321deg, #0077ce 0%, #4ec0ff 100%);
      border-radius: 200rpx 200rpx 200rpx 200rpx;
    }
    &.dark {
      background: linear-gradient(321deg, #2f353a 0%, #1c1f22 100%);
      border-radius: 100rpx 100rpx 100rpx 100rpx;

      box-shadow: inset 0rpx 0rpx 3rpx 0rpx rgba(63, 63, 63, 0.45);
    }
    &.mb-30 {
      margin-bottom: 30rpx;
    }
  }
  .jiantou {
    .a {
      transform: rotate(90deg);
    }
    .b {
      transform: rotate(-90deg);
    }
  }
}
.clock {
  width: 15%;
  border-radius: 50%;
  position: relative;
  transform: rotateY(180deg);
}
::v-deep .uni-mask {
  background-color: rgb(0, 0, 0, 0.6) !important;
}
</style>
<style lang="scss">
page {
  overflow-x: hidden;
}
</style>
